package com.study.servlet.cookie.prac02;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.study.servlet.cookie.prac02.domain.Book;

/**
* @Name: ShowAllProducts
* @Description: Cookie实现浏览记录的保存
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-3-1 下午10:07:31 
* @Version: V1.0
 */
public class ShowAllProducts extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8") ;
		PrintWriter out = response.getWriter() ;
		//显示所有商品
		out.write("本网站提供有如下奇葩书籍，请笑纳:<br/>");
		Map<String, Book> allBooks = BookDB.getAllBooks() ;
		for(Map.Entry<String, Book> entry : allBooks.entrySet()) {
			Book book = entry.getValue() ;
			out.write(book.getName()+ "&nbsp;" +
					"<a href='"+request.getContextPath()+"/servlet/ShowDetail?id="+book.getId()+"'>查看详情</a><br/>") ;
		}
		//查看历史记录
		out.write("<br/><br/>您浏览过的书籍如下：<br/>");
		//读Cookie才知道
		Cookie[] cookies = request.getCookies() ;
		if(cookies != null && cookies.length > 0) {
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i] ;
				if("HistoryBooks".equals(cookie.getName())) {
					//取出书的id   1-3-4   2-1-3
					String[] ids = cookie.getValue().split("-") ;
					for (int j = 0; j < ids.length; j++) {
						Book book = BookDB.getBookById(ids[j]) ;
						out.write(book.getName()+"<br/>");
					}
				}
			}
		}
		out.flush() ;
		out.close() ;
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
